package com.base.cn.platform.os.controller.course.open;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.course.MaterialType;
import com.base.cn.platform.os.common.utils.file.FileDownloadUtil;
import com.base.cn.platform.os.common.utils.ke96.Ke96ServiceUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.service.course.cloud.CloudService;
import com.base.cn.platform.os.service.course.open.CourseOpenService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 免费直播后台管理Controller
 *
 * @author s.li
 * @create 2018-05-03-16:42
 */
@Controller
@RequestMapping("/admin/course/open")
public class AdminCourseOpenController extends AdminBaseController {

    @Autowired
    private CourseOpenService courseOpenService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CloudService cloudService;
    @Autowired
    private Ke96ServiceUtils ke96ServiceUtils;
    /**
     * 初始化免费直播列表页面
     * @return 列表页面
     */
    @RequestMapping("/courseOpenList")
    public String courseOpenList(Model model){
        TreeMap<String, String> sysConfigContext = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        model.addAttribute("ccAppId",sysConfigContext.get("ccAppId"));
        return resultPage("/course/open/courseOpen-list");
    }

    /**
     * 获取免费直播数据列表页面
     * @param currentPage 页码
     * @param params 查询条件
     * @return 数据列表
     */
    @RequestMapping("/ajaxCourseOpenList")
    public String ajaxCourseOpenList(Model model,
                                     @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                     @RequestBody Map<String,Object> params){
        Map<String,Object> dataMap = courseOpenService.findCourseOpenPage(params,currentPage,null,true,true,true,false);
        model.addAttribute("dataMap",dataMap);
        return resultPage("/course/open/ajax-courseOpen-list");
    }

    /**
     * 复制后台直播路径
     * @param id 课程ID
     * @return Map<String,Object>
     */
    @RequestMapping("/getAdminCopyLiveUrl")
    @ResponseBody
    public Map<String,Object> getAdminCopyLiveUrl(@RequestParam("id") BigDecimal id){
        String url = courseOpenService.getAdminCopyLiveUrl(id);
        return ResultUtil.SUCCESS("复制成功",url);
    }

    /**
     * 初始化添加/修改免费直播
     * @param id 免费直播ID（用于修改）
     * @return 操作页面
     */
    @RequestMapping(value = {"/initUpdate","/initAdd"})
    public String initUpdateOrAdd(Model model,
                                  @RequestParam(value = "id",required = false,defaultValue = "0") BigDecimal id) throws IOException{
        TreeMap<String,String> vlasProviderMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        model.addAttribute("vlasProviderMap",vlasProviderMap);
        Map<String,Object> courseOpen = null;
        if(DataUtil.idIsNotNull(id)){
            courseOpen = courseOpenService.findCourseOpenById(id,false,true,false);
            if(ObjectUtils.isNotEmpty(courseOpen) && ObjectUtils.isEmpty(courseOpen.get("replayUrl"))){
                courseOpen = getLiveReplayUrl(courseOpen);
            }
        }
        if(courseOpen==null){
            courseOpen = new HashMap<>();
        }
        model.addAttribute("courseOpen", courseOpen);
        if (ObjectUtils.isEmpty(courseOpen)) {
            if (vlasProviderMap.get("type").equals("CC")) {
                return resultPage("/course/open/save-courseOpen-cc");
            } else {
                return resultPage("/course/open/save-courseOpen-tt");
            }
        } else {
            if ("CC".equals(courseOpen.get("playType"))) {
                List<Map> playback = cloudService.findCCPlaybackPage(courseOpen.get("roomId").toString());
                model.addAttribute("playback", playback);
                return resultPage("/course/open/save-courseOpen-cc");
            } else {
                return resultPage("/course/open/save-courseOpen-tt");
            }
        }
    }

    /**
     * 保存免费直播数据
     * @param request
     * @param courseOpen 免费直播数据对象
     * @return Map<String,Object>
     */
    @RequestMapping("/saveCourseOpen")
    @ResponseBody
    public Map<String,Object> saveCourseOpen(HttpServletRequest request,
                                             @RequestBody Map<String, Object> courseOpen){
        courseOpen.put("createUserId",loginUtil.getLoginUserId(request));
        return courseOpenService.saveCourseOpen(courseOpen);
    }

    /**
     * 设置免费直播描述信息
     * @param id 免费直播ID
     * @return 操作页面
     */
    @RequestMapping("/initCourseOpenInfo")
    public String initCourseOpenInfo(Model model,@RequestParam("id") BigDecimal id){
        Map<String,Object> courseOpen = courseOpenService.findCourseOpenById(id,false,true,false);
        model.addAttribute("courseOpen",courseOpen);
        return resultPage("/course/open/save-courseOpen-depict");
    }

    /**
     * 保存免费直播描述信息
     * @param courseOpen
     * @return Map<String,Object>
     */
    @RequestMapping("/saveCourseOpenInfo")
    @ResponseBody
    public Map<String,Object> saveCourseOpenInfo(@RequestBody Map<String,Object> courseOpen){
        return courseOpenService.saveCourseOpenInfo(courseOpen);
    }

    /**
     * 修改免费直播状态
     * @param ids 免费直播ID串
     * @param status 状态， 1：正常 2：冻结 3：删除
     * @return Map<String,Object>
     */
    @RequestMapping("/updateCourseOpenStatus")
    @ResponseBody
    public Map<String,Object> updateCourseOpenStatus(@RequestParam("ids") String ids,
                                                     @RequestParam("status") int status){
        return courseOpenService.updateCourseOpenStatus(ids,status);
    }

    /**
     * 查看免费直播详情
     * @param id 免费直播ID
     * @return 显示页面
     */
    @RequestMapping("/showCourseOpenInfo")
    public String showCourseOpenInfo(Model model,
                                     @RequestParam("id") BigDecimal id) throws IOException{
        Map<String,Object> courseOpen = courseOpenService.findCourseOpenById(id,true,true,true);
        if(ObjectUtils.isNotEmpty(courseOpen) && ObjectUtils.isEmpty(courseOpen.get("replayUrl"))){
            courseOpen = getLiveReplayUrl(courseOpen);
        }
        model.addAttribute("courseOpen",courseOpen);
        return resultPage("/course/open/courseOpen-info");
    }

    /**
     * 开始免费直播直播
     * @param id   免费直播id
     * @param auth 认证当前用户与直播讲师一致
     * @return 直播地址
     */
    @RequestMapping("/live/start")
    @ResponseBody
    public Map<String, Object> startCourseOpenLive(HttpServletRequest request,
                                                   @RequestParam("id") BigDecimal id,
                                                   @RequestParam(value = "auth", defaultValue = "false", required = false) Boolean auth) {
        BigDecimal sysUserId = loginUtil.getLoginUserId(request);
        return courseOpenService.startAdminCourseOpenLive(id, sysUserId, auth);
    }

    /**
     * 初始化选择免费直播列表页面
     * @return 列表页面
     */
    @RequestMapping("/selectCourseOpenList")
    public String selectCourseOpenList(Model model,
                                       @RequestParam(value = "selectType",required = false,defaultValue = "checkbox") String selectType,
                                       @RequestParam(value = "subjectIds",required = false,defaultValue = "") String subjectIds){
        model.addAttribute("selectType",selectType);
        model.addAttribute("subjectIds",subjectIds);
        return resultPage("/course/open/select-open-course-list");
    }

    /**
     * 获取选择免费直播数据列表页面
     * @param currentPage 页码
     * @param params 查询条件
     * @return 数据列表
     */
    @RequestMapping("/selectAjaxCourseOpenList")
    public String selectAjaxCourseOpenList(Model model,
                                     @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                     @RequestBody Map<String,Object> params){
        params.put("status",1);
        Map<String,Object> dataMap = courseOpenService.findCourseOpenPage(params,currentPage,null,true,false,false,false);
        model.addAttribute("dataMap",dataMap);
        model.addAttribute("selectType",params.get("selectType"));
        return resultPage("/course/open/select-open-course-ajax-list");
    }


    /**
     * 获取直播回放地址
     * @return
     */
    public Map<String,Object> getLiveReplayUrl(Map<String,Object> courseOpen) throws IOException {
        if(courseOpen.get("liveBilling").toString().equals("1")){//小班
            //获取小班课回放地址
            String url = "http://api.csslcloud.net/api/v2/record/info";
            Map<String, Object> params = new HashMap<>();
            params.put("roomid",courseOpen.get("roomId"));
            Map<String, Object> resultMap = ke96ServiceUtils.demandSmall(url,params);
            if(resultMap.get("result").equals("OK")){
                List<Map<String,Object>> resultList = (List<Map<String, Object>>) resultMap.get("records");
                if(ObjectUtils.isNotEmpty(resultList)){
                    String replayUrl = "";
                    for(int i=1;i<=resultList.size();i++){
                        if(ObjectUtils.isNotEmpty(resultList.get(i-1).get("replayUrl"))){
                            if(StringUtils.isNotEmpty(replayUrl)){
                                replayUrl = replayUrl + " 回放"+i+":"+resultList.get(i-1).get("replayUrl");
                            }else{
                                replayUrl = "回放"+i+":"+resultList.get(i-1).get("replayUrl");
                            }
                        }
                    }
                    courseOpen.put("replayUrl",replayUrl);
                    courseOpenService.saveCourseOpen(courseOpen);
                }
            }
        }else{
            //获取直播回放地址
            String url = "http://api.csslcloud.net/api/v2/record/info";
            Map<String, Object> params = new HashMap<>();
            params.put("roomid",courseOpen.get("roomId"));
            Map<String, Object> resultMap = ke96ServiceUtils.demandLive(url,params);
            if(resultMap.get("result").equals("OK")){
                List<Map<String,Object>> resultList = (List<Map<String, Object>>) resultMap.get("records");
                if(ObjectUtils.isNotEmpty(resultList)){
                    String replayUrl = "";
                    for(int i=1;i<=resultList.size();i++){
                        if(ObjectUtils.isNotEmpty(resultList.get(i-1).get("replayUrl"))){
                            if(StringUtils.isNotEmpty(replayUrl)){
                                replayUrl = replayUrl + " 回放"+i+":"+resultList.get(i-1).get("replayUrl");
                            }else{
                                replayUrl = "回放"+i+":"+resultList.get(i-1).get("replayUrl");
                            }
                        }
                    }
                    courseOpen.put("replayUrl",replayUrl);
                    courseOpenService.saveCourseOpen(courseOpen);
                }
            }
        }
        return courseOpen;
    }

    /**
     * 下载直播上课记录
     * @param request
     */
    @RequestMapping("/downloadExcel")
    public ResponseEntity<byte[]> downloadExcelUserLiveRecord(HttpServletRequest request,
                                                              @RequestParam("courseOpenId") BigDecimal courseOpenId) throws Exception{
        Map<String,Object> courseOpen = courseOpenService.findCourseOpenById(courseOpenId,false,false,false);

        //表格头部
        String [] heads = new String[] {"用户ID","用户昵称","用户ip","观看时长","进入时间","离开时间","终端类型"};
        //生成文件的容器
        List<Map<String,Object>> srcFile = new ArrayList<>();
        //文件名
        String expName = "上课记录"+System.currentTimeMillis();
        //获取数据
        List<Map<String,Object>>  userLiveRecordList = new ArrayList<>();
        if(courseOpen.get("liveBilling").toString().equals("1")){//互动小班直播
            userLiveRecordList = ke96ServiceUtils.smallLiveVisitData(courseOpen.get("roomId").toString(),courseOpen.get("openTime").toString(),courseOpen.get("endTime").toString());
            ke96ServiceUtils.generateFile(ke96ServiceUtils.getSmallLiveData(userLiveRecordList),heads,expName+".xls",srcFile);
        }else{//并发直播
            userLiveRecordList = ke96ServiceUtils.liveVisitData(courseOpen.get("roomId").toString());
            ke96ServiceUtils.generateFile(ke96ServiceUtils.getLiveData(userLiveRecordList),heads,expName+".xls",srcFile);
        }

        return FileDownloadUtil.createRar(srcFile,expName);
    }
}
